import { asyncRoutes, constantRoutes } from '@/router'

// /**
//  * Use meta.role to determine if the current user has permission
//  * @param roles
//  * @param route
//  */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }

function hasPermission(menuList, route, sysMgr) {
  if(route&&route.meta&&route.meta.key){
    let flag = menuList.some(menu => route.meta.key===(menu.menuPath))
    if(sysMgr){
      return flag && (route.path.indexOf("/sys")!==-1)
    }else{
      return flag && (route.path.indexOf("/sys")===-1)
    }
  }else{
    return true;
  }
}

/**
 * 根据MenuList构建Router
 * @param routes
 * @param menuList
 * @param sysMgr 是否是系统管理
 */
export function filterAsyncRoutes (routes,menuList,sysMgr) {
  // const res = []

  // routes.forEach(route => {
  //   const tmp = { ...route }
  //   if (hasPermission(menuList, tmp,sysMgr)) {
  //     if (tmp.children) {
  //       tmp.children = filterAsyncRoutes(tmp.children, menuList,sysMgr)
  //     }
  //     res.push(tmp)
  //   }else{
  //     //如果没有包含 但是这个节点有子节点已经在权限内 则菜单也显示
  //     if (tmp.children) {
  //       tmp.children = filterAsyncRoutes(tmp.children, menuList,sysMgr)
  //     }
  //     if(tmp.children && tmp.children.length>0){
  //       res.push(tmp)
  //     }
  //   }
  // })
  // return  res
  return routes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit ,state}, menuObj) {
    const {menuList,sysMgr} =menuObj
    return new Promise(resolve => {
      let accessedRoutes = filterAsyncRoutes(asyncRoutes, menuList,sysMgr)
      // console.log("accessRouters:"+JSON.stringify(accessedRoutes))
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
